Page({
	quality: 0.5, // 图片质量
	WHScale: 1, // 尺寸大小比例
	imageList: [], // 存储旧新图片信息
	originalImageList: [], // 用户初始添加的图片列表
	data: {
		changeQualityValue: 50,
		changeWHValue: 100,
		imageListIndex: 0, // 默认展示的图片列表下标
	},
	onReady() {

	},
	chooseImage() {
		wx.showActionSheet({
			itemList: ['从聊天会话选择', '从相册选择', '拍照'],
			success: async res => {
				if (res.tapIndex === 0) {
					let res2 = await wx.chooseMessageFile({
						count: 20,
						type: 'image',
					})
					this.originalImageList = res2.tempFiles
				} else if (res.tapIndex === 1) {
					// 选择本地图片
					let res2 = await wx.chooseMedia({
						count: 20,
						mediaType: ['image'],
						sourceType: ['album'],
						sizeType: ['original'],
					})
					this.originalImageList = res2.tempFiles
				} else {
					// 选择本地图片
					let res2 = await wx.chooseMedia({
						count: 20,
						mediaType: ['image'],
						sourceType: ['camera'],
						sizeType: ['original'],
					})
					this.originalImageList = res2.tempFiles
				}
				if (this.originalImageList.length === 1) {
					await this.startImageCompress(this.originalImageList)
				} else {
					wx.setStorageSync('originalImageList', this.originalImageList)
					wx.navigateTo({
						url: '/pages/imageTools/pages/moreImageCompression/index',
					})
				}
			},
			fail: err => {
				console.log(err.errMsg)
			}
		})
	},
	// 开始压缩图片
	async startImageCompress(tempFiles = []) {
		this.imageList = [] // 重置列表
		for (let index = 0; index < tempFiles.length; index++) {
			wx.showLoading({
				title: `正在压缩`,
			})
			const item = tempFiles[index];
			// 1、设定新的imageList
			this.imageList.push({
				oldImage: {}, // 存储旧信息
				newImage: {} // 存储新信息
			})
			// 2、将图的旧信息放到oldImage中
			let res = await this.getImageInfo(item.path || item.tempFilePath)
			this.imageList[index].oldImage = {
				...res.data
			}
			this.setData({
				imageList: this.imageList
			})
			// 3、开始将图片绘制并导出
			let res2 = await this.drawImageToCanvas(item.path || item.tempFilePath, res.data.width * this.WHScale, res.data.height * this.WHScale)
			this.imageList[index].newImage = res2.data
			this.setData({
				imageList: this.imageList
			})
			wx.hideLoading()
		}
	},
	// 绘图
	async drawImageToCanvas(path, width, height) {
		return new Promise(resolve => {
			try {
				this.setData({
					canvasWidth: width,
					canvasHeight: height
				})
				const ctx = wx.createCanvasContext('myCanvas')
				ctx.drawImage(path, 0, 0, width, height)
				ctx.draw(false, async () => {
					// 导图
					let res = await this.canvasToImage(width, height)
					resolve(res)
				})
			} catch (error) {
				console.error(error)
				resolve({
					code: false,
					data: '图片绘制错误'
				})

			}
		})
	},
	// 导图
	async canvasToImage(width, height) {
		return new Promise(resolve => {
			wx.canvasToTempFilePath({
				x: 0,
				y: 0,
				width,
				height,
				destWidth: width,
				destHeight: height,
				quality: this.quality,
				fileType: 'jpg',
				canvasId: 'myCanvas',
				success: async res => {
					// 获取导出图的信息
					let res2 = await this.getImageInfo(res.tempFilePath)
					resolve(res2)
				},
				fail: err => {
					console.log(err)
					resolve({
						code: false,
						data: '图片导出错误'
					})
				}
			})
		})
	},
	// 读取指定路径图片尺寸信息
	async getImageInfo(path) {
		return new Promise(resolve => {
			wx.getImageInfo({
				src: path,
				success: res => {
					wx.getFileSystemManager().getFileInfo({
						filePath: path,
						success: res2 => {
							resolve({
								code: true,
								data: {
									path: path,
									size: this.imageSizeTurn(res2.size),
									width: res.width,
									height: res.height
								}
							})
						},
						fail: err2 => {
							console.error(err2)
							resolve({
								code: false,
								data: '获取图片大小出错'
							})
						}
					})
				},
				fail: err => {
					console.error(err)
					resolve({
						code: false,
						data: '获取图片尺寸出错'
					})
				}
			})
		})
	},
	// 将B转为KB或MB
	imageSizeTurn(size) {
		if (size > 1024 * 1024) {
			size = Number((size / 1024 / 1024).toFixed(2)) + 'MB'
		} else if (size > 1024 && size <= 1024 * 1024) {
			size = Number((size / 1024).toFixed(2)) + 'KB'
		}
		return size
	},
	// 修改图片质量
	async changeQuality(e) {
		if (this.originalImageList.length === 0) {
			this.setData({
				changeQualityValue: this.quality * 100
			})
			wx.showToast({
				title: '请先选择图片',
				icon: 'none'
			})
			return
		}
		this.quality = e.detail.value / 100
		await this.startImageCompress(this.originalImageList)
	},
	// 修改图片尺寸
	async changeWH(e) {
		if (this.originalImageList.length === 0) {
			this.setData({
				changeWHValue: this.WHScale * 100
			})
			wx.showToast({
				title: '请先选择图片',
				icon: 'none'
			})
			return
		}
		this.WHScale = e.detail.value / 100
		await this.startImageCompress(this.originalImageList)
	},
	// 预览压缩图
	previewImage() {
		wx.previewImage({
			current: this.imageList[this.data.imageListIndex].newImage.path,
			urls: [this.imageList[this.data.imageListIndex].newImage.path],
		})
	},
	// 保存图片到相册
	saveImage() {
		if (this.originalImageList.length === 0) {
			return wx.showToast({
				title: '请先选择图片',
				icon: 'none'
			})
		}
		for (let index = 0; index < this.imageList.length; index++) {
			const item = this.imageList[index];
			wx.saveImageToPhotosAlbum({
				filePath: item.newImage.path,
				success: res => {
					wx.showToast({
						title: `图片已保存`,
						icon: 'none'
					})
				},
				fail: err => {
					console.log(err)
					wx.showToast({
						title: '图片保存失败',
						icon: 'error'
					})
				}
			})
		}

	},
	onShareAppMessage() {
    return {
      title: "图片压缩神器，不再为大图而烦恼",
      path: "/pages/imageTools/pages/imageCompression/index",
      imageUrl: '/images/function_icon/imageCompression.jpeg',
    }
  },
  onShareTimeline() {
    return {
      title: '图片压缩神器，不再为大图而烦恼',
      imageUrl: '/images/function_icon/imageCompression.jpeg',
    }
  },
})

function sleep(ms) {
	console.log('延时=========')
	return new Promise(resolve => setTimeout(resolve, ms))
}